#!/usr/bin/python 
# -*- coding=utf-8 -*-
'''
master-client server
handling client request
'''
import tornado.ioloop
import tornado.web
from handler.BlockHandler import BlockHandler
from handler.LoadBalanceHandler import LoadBalanceHandler
import logging
import platform
import socket
import zc.zk

class Server():
    def __init__(self, conf):
        self.conf = conf
        self.logger = logging.getLogger('master')

    def start(self):
        # register server
        meta_server = self.conf.get('all', 'meta-server')
        self.logger.info('meta server address: %s' % meta_server)
        # connect meta
        zk = zc.zk.ZooKeeper(meta_server)
        self.logger.info('connect to meta success')
        # register server
        server_ip = socket.gethostbyname(platform.node())
        server_port = self.conf.get('master', 'server-port')
        try:
            zk.register_server('/iotmq/master', (server_ip, server_port))
            self.logger.info('register server(%s:%s) success', server_ip, server_port)
        except Exception, e:
            self.logger.exception('register server failed, %s' % str(e))

        lb = LoadBalanceHandler()
        settings = {
            'zookeeper' : zk,
            'loadbalancer': lb,
        }
        self.app = tornado.web.Application([
                (r'/test', TestHandler),
                (r'/([0-9a-zA-Z\-]+)/([0-9]*)', BlockHandler, dict(zk = settings['zookeeper'],
                                                                   lb = settings['loadbalancer'])),
                ])
        self.app.listen(self.conf.get('master','server-port'))
        self.logger.info('server start to listen...')
        tornado.ioloop.IOLoop.instance().start()

# test
class TestHandler(tornado.web.RequestHandler):
    def get(self):
        self.write('server OK.')

if __name__ == '__main__':
    from ConfigParser import ConfigParser
    conf = ConfigParser()
    conf.read('./conf/master.conf')
    s = Server(conf)
    s.start()
